﻿using System;

namespace Graph
{
    public class Edge
    {         
        private Vertex _vertex1;
        private Vertex _vertex2;
        public int? Length { get; set; }

        public Vertex Vertex1
        {
            get { return _vertex1; }

            private set
            {
                if (value != null)
                    _vertex1 = value;
                else                
                    throw new ArgumentException("Vertex should not be null");                
            }             
        }

        public Vertex Vertex2
        {
            get { return _vertex2; }
            
            private set
            {
                if (value != null)
                    _vertex2 = value;
                else
                    throw new ArgumentException("Vertex should not be null");                
            }
        } 

        public Edge(Vertex vertex1, Vertex vertex2, int? length = null)
        {
            if (!vertex1.Equals(vertex2))
            {
                Vertex1 = vertex1;
                Vertex2 = vertex2;
                Length = length;
            }
            else
                throw new ArgumentException("The edge has two equal vertices");
        }

        public Edge(string vertex1, string vertex2, int? length = null)
            : this(new Vertex(vertex1), new Vertex(vertex2), length)
        {            
        }

        public Edge(Edge edge) 
            : this(edge.Vertex1, edge.Vertex2, edge.Length)
        {            
        }

        public sealed override bool Equals(object obj)
        {
            Edge edge = obj as Edge;

            return edge != null 
                &&  ((this.Vertex1.Equals(edge.Vertex1) && this.Vertex2.Equals(edge.Vertex2))
                ||  (this.Vertex1.Equals(edge.Vertex2) && this.Vertex2.Equals(edge.Vertex1)));
        }

        public sealed override int GetHashCode()
        {
            return Vertex1.GetHashCode() ^ Vertex2.GetHashCode();
        }

        public override string ToString()
        {
            return String.Format("{0} {1}", Vertex1.Name, Vertex2.Name);
        }
    }
}
